<template>
  <q-page class="column">
    <q-inner-loading visible v-if="model.noticeId < 0">
      <q-spinner-gears size="50px" color="primary"></q-spinner-gears>
      <b class="text-primary">数据加载中...</b>
    </q-inner-loading> 

    <!-- create new -->
    <div v-if="model.noticeId>=0">
      <q-list class="sms col q-py-none" no-border v-if="model.noticeId>=0">
        <q-list-header>选择模板</q-list-header>
        <q-item>
          <q-select class="full-width" hide-underline placeholder="请选择固定模板的类型"
            radio v-model="model.config" :options="templateOptions" @input="selectTemplate" />
        </q-item>

        <q-list-header class="row">
          <span class="col">选择活动</span>
          <small class="col-auto text-primary">(选填，选择后会自动设置参数值)</small>
        </q-list-header>
        <q-item>
          <q-input readonly class="full-width" v-model="currentEvent.movie" hide-underline placeholder="未选择" @click="modal=true" />
          <q-btn flat dense icon="mdi-settings" color="primary" @click="modal=true" />
        </q-item>

        <q-list-header class="row">
          <span class="col">短信标题</span>
          <small class="col-auto text-primary">(便于快速识别短信内容)</small>
        </q-list-header>
        <q-item>
          <q-input class="full-width" v-model="model.title" hide-underline placeholder="便于快速识别短信内容" />          
        </q-item>
        
        <q-list-header class="row">
          <span class="col">发送渠道</span>
        </q-list-header>
        <q-item>
          <q-item-side>发送渠道：</q-item-side>
          <q-item-main>{{ model.channel == 'ALIYUN' ? '阿里云' : (model.channel == 'ALIYUN_OLD' ? '阿里云(旧)' : '腾讯云') }}</q-item-main>
        </q-item>

        <q-list-header class="row">
          <span class="col">短信内容</span>
          <small class="col-auto text-primary">(补充参数后，自动内容自动刷新)</small>
        </q-list-header>
        <q-item>
          <q-input readonly class="full-width" type="textarea" rows="3" hide-underline 
              :value="parsedContent" placeholder="需发送的短信内容(模板)" />
        </q-item>

        <q-list-header class="row">
          <span class="col">手机号</span>
          <small class="col-auto text-primary">(建议直接复制Excel表中的对应数据列)</small>
        </q-list-header>
        <q-item>
          <q-input class="full-width" type="textarea" rows="3" :max-height="75" hide-underline
              placeholder="中奖用户手机号，每行一条手机号" v-model="model.userIds"/>
        </q-item>

        <template v-if="paramNames.length > 0">
          <div v-for="(item,idx) in paramNames" :key="'pn'+item+idx">
            <q-list-header class="row">短信参数【{{item}}】</q-list-header>
            <q-item>
              <q-input class="full-width" hide-underline v-model="model.params[idx]"
                  placeholder="必填，最多20个字符" />
            </q-item>
          </div>
        </template>
      </q-list>
    </div>

    <!-- save -->
    <q-btn color="primary" class="fixed" label="保存" icon="mdi-content-save"
        style="right: 15px; bottom: 15px"
        v-if="model.noticeId>=0" :loading="loading" @click="save" />

    <!-- modal -->
    <q-modal v-model="modal" :position="$q.platform.is.mobile?'':'right'" :maximized="$q.platform.is.mobile"
      @show="loadEvents">
      <q-toolbar color="primary">
        <q-toolbar-title>选择活动</q-toolbar-title>
        <q-btn flat round dense icon="mdi-close" @click="modal=false" />
      </q-toolbar>

      <q-inner-loading visible v-if="list.length <= 0">
        <q-spinner-gears size="50px" color="primary"></q-spinner-gears>
        <b class="text-primary">数据加载中...</b>
      </q-inner-loading>

      <q-list separator no-border v-if="list.length > 0">
        <q-item v-for="item in list" :key="item.id">
          <q-item-side>
            <q-item-tile class="relative-position">
              <q-chip detail small square icon="mdi-calendar-clock">
                {{item.date.substring(5).replace('-', '月')+'日'}}
              </q-chip>
              <q-chip floating v-if="item.days>=0" 
                  :color="item.days>0?'green':'primary'">
                {{item.days == 0 ? '今' : Math.abs(item.days)}}
              </q-chip>
            </q-item-tile>
            <q-item-tile>
              <q-chip detail small square icon="mdi-progress-clock">{{item.timeBegin}}</q-chip>
            </q-item-tile>
            <q-item-tile>
              <q-chip detail small square icon="mdi-city">{{item.city}}</q-chip>
            </q-item-tile>
          </q-item-side>
          <q-item-main>
            <q-item-tile label lines="1" class="q-mb-md">{{item.movie}}</q-item-tile>
            <q-item-tile sublabel lines="1">{{item.title}}</q-item-tile>
            <small><q-item-tile sublabel lines="1">{{item.cinema}}</q-item-tile></small>
          </q-item-main>
          <q-item-side>
            <q-radio v-model="eventId" :val="item.id" @input="selectEvent(item)"/>
          </q-item-side>
        </q-item>
      </q-list>
    </q-modal>
  </q-page>
</template>

<script>
export default {
  name: 'PageSmsTemplateCodeEdit',
  data() {
    return {
      modal: false,
      loading: false,
      eventId: 0,
      currentEvent:{ id:0,movie:'' },
      currentTemplate:{},
      model : {
        noticeId : -1,
        title: '',
        content: '',
        userIds: '',
        params:[],
        channel: 'ALIYUN'
      },
      list:[]
    }
  },
  mounted() {
    let me = this;
    me.loadModel(this.$route.params.id);
    this.$api.ui.pageBackBtn = function(){
      if(me.model.noticeId > 0) {
        me.$router.push('/sms-code/view2/' + me.model.noticeId);
      } else {
        me.$router.push('/sms-code');
      }
    }
  },
  methods: {
    refreshParam() {
      if(this.currentEvent.id > 0) {        
        let pNames = this.paramNames;
        for(let idx in pNames) {
          let name = pNames[idx];
          let value = this.currentEvent[name];
          this.model.params[idx] = (value ? value : '');
          //this.model.params.push(value ? value : '');
        }
        this.model.title = this.currentEvent.date + "《" + this.currentEvent.movie + "》" 
          + (this.currentTemplate.title?this.currentTemplate.title:"");
      } else {
        // event未知，猜电影名称
        let idxStart = this.model.title.indexOf("《");
        let idxEnd = this.model.title.indexOf("》");
        if(idxStart>=0 && idxEnd>=0) {
          this.currentEvent.movie = this.model.title.substring(idxStart + 1, idxEnd);
        }
      }
    },
    selectTemplate(tid) {
      this.currentTemplate = this.$api.notice.selectSmsTemplate(tid);
      this.model.config = tid;
      this.model.content = this.currentTemplate.content;
      this.model.channel = this.currentTemplate.title.startsWith('阿里') ? "ALIYUN" : "QCLOUD";
      this.refreshParam();
    },
    selectEvent(item) {
      this.currentEvent = item;
      this.model.content = this.currentTemplate.content + ' ';
      this.modal = false;
      this.refreshParam();
    },
    loadEvents() {
      if(this.list && this.list.length > 0) {
        return;
      }
      let me = this;
      this.$api.notice.loadEvents(res=>{
        for(let idx in res.data.model) {
          let m = res.data.model[idx];
          let tmp = m.movie;
          m.movie = m.movie2;
          m.movie2 = tmp;
        }
        me.list = res.data.model;
      });
    },

    loadModel(id) {
      let me = this;
      if(id <= 0) {
        this.model = { noticeId : 0, title: '', content: '', userIds: '', params:[], channel: 'ALIYUN'  }
      } else {
        this.$api.notice.loadOne(id, res=>{
          let templateParams = res.data.model.content;  // 使用content来存储通用参数, @_@ 作为分隔符；
          let paramsAndContent = templateParams.split('~@~');
          me.model = res.data.model;
          me.model.content = paramsAndContent[0];
          me.model.params = paramsAndContent[1].split('@_@');
          me.selectTemplate(me.model.config)
        });
      }
    },
    save() {    
      if(!this.doCheck()) {
         return;  // 检验不通过
      }
      let me = this;
      this.loading = true;
      this.$api.notice.saveSmsCode({
        noticeId : me.model.noticeId,
        title: me.model.title,
        config: me.model.config,
        // 使用content来存储通用参数, @_@ 作为分隔符；~@~ 分割参数和模板，不能变！
        content: me.currentTemplate.content + '~@~' + me.stringTemplateParams(),   
        userIds: me.model.userIds,
        params:[],
        channel: me.model.channel
      }, res=>{
        let id = res.data.model.noticeId;
        me.$q.notify({
          message: '保存成功',
          type: 'positive',
          color: 'positive',
          icon: 'mdi-check'
        });
        me.$router.push('/sms-code/view2/' + id);
      }, err=>{
        this.loading = false;
      });
    },
    doCheck() {
      let me = this;
      let pNames = this.paramNames;
      for(let idx in pNames) {
        let value = this.model.params[idx];
        if(!value || value.trim().length == 0) {
          me.$q.notify({
            message: '参数【'+pNames[idx]+'】必须填写',
            type: 'negative',
            color: 'negative'
          });
          return false;
        } else if(value.length > 20) {
          me.$q.notify({
            message: '参数【'+pNames[idx]+'】不能超过20个字符',
            type: 'negative',
            color: 'negative'
          });
          return false;
        }        
      }
      return true;
    },
    stringTemplateParams() {
      let str = this.model.params[0];
      for(let i = 1; i < this.model.params.length; i++) {
        str += ('@_@' + this.model.params[i]);
      }
      return str;
    }
  },
  computed: {
    templateOptions() {
      return this.$api.notice.smsTemplateOptions();
    },
    paramNames() {
      let tmpl = this.model.content;
      let array = tmpl.split('${');
      let size = array.length;
      if(size == 1) {
        // 无参数
        return [];
      } else {
        try {
          let names = [];
          for(let i = 1; i < size; i++) {
            names.push(array[i].substring(0, array[i].indexOf('}')));
          }
          return names;
        } catch {
          return [];
        }
      }
    },
    parsedContent() {
      let pNames = this.paramNames;
      let content = this.model.content;
      for(let idx in pNames) {
        let value = this.model.params[idx];
        if(value) {
          content = content.replace('${' + pNames[idx] + '}', this.model.params[idx]);
        }
      }
      return content;
    }
  }
}
</script>

<style>
div.sms .q-list-header {
  background-color: #eee;
  padding: 15px 10px 3px 10px;
  min-height: 30px;
}
</style>


